var app=getApp()
var moduleUrl=app.baseUrl+'/client/event'
Page({
  data: {
    form:[
      {
        title:"姓名",
        value:"",
        required: true
      },
      {
        title:"手机号",
        value:"",
        required: true
      },
    ],
    eventTitle:"活动一",
    eventId:"1",
    focusIndex: -1,
    errorMessage: '',
    formValid: false  // 新增表单验证状态
  },
  onLoad(e) {
    
    this.setData({
      eventId:e.id,
      eventTitle:e.eventTitle
    })
  },
  // 新增输入框聚焦交互
  onInputFocus(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ 
      focusIndex: index,
      errorMessage: '' 
    });
  },

  // 新增输入框值变化事件
  onInputChange(e) {
    const { value } = e.detail;
    const index = e.currentTarget.dataset.index;
    
    // 更新表单数据
    const newForm = [...this.data.form];
    newForm[index].value = value;
    this.setData({ form: newForm });

    // 实时验证
    this.validateForm();
  },

  // 修改输入框失焦验证
  onInputBlur(e) {
    const { value } = e.detail;
    const index = e.currentTarget.dataset.index;
    const field = this.data.form[index];
    
    // 更新表单数据
    const newForm = [...this.data.form];
    newForm[index].value = value;
    this.setData({ 
      form: newForm,
      focusIndex: -1 
    });

    // 只在失焦时显示错误信息
    if (field.required && !value.trim()) {
      this.setData({ 
        errorMessage: `${field.title}不能为空`
      });
      return;
    }
    
    if (field.title === '手机号') {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        this.setData({ 
          errorMessage: '请输入有效的手机号码'
        });
        return;
      }
    }

    this.setData({ errorMessage: '' });
  },

  validateForm() {
    const { form } = this.data;
    let isValid = true;

    // 检查必填字段
    for (const field of form) {
      if (field.required && !field.value.trim()) {
        isValid = false;
        break;
      }
      
      // 手机号格式验证
      if (field.title === '手机号' && field.value) {
        if (!/^1[3-9]\d{9}$/.test(field.value)) {
          isValid = false;
          break;
        }
      }
    }

    this.setData({ formValid: isValid });
  },

  // 优化提交逻辑
  async applyevent(e) {
    if (this.data.isSubmitting) return;
    
    // 提交前再次验证表单
    this.validateForm();
    if (!this.data.formValid) {
      dd.showToast({
        type: 'fail',
        content: this.data.errorMessage || '请完善表单信息',
        duration: 2000
      });
      return;
    }

    this.setData({ isSubmitting: true });
    
    try {
      const res = await dd.httpRequest({
        url: moduleUrl+'/apply',
        method: 'POST',
        headers: {
          "Content-Type": "application/json"
        },
        data: JSON.stringify({
          eventId: this.data.eventId,
          userId: app.userId,
          userName: this.data.form[0].value,
          phone: this.data.form[1].value
        })
      });

      if(res.data.status == 200) {
        await dd.showToast({
          type: 'success',
          content: res.data.data,
          duration: 1500
        });
        
        const pages = getCurrentPages();
        if (pages.length > 2) {
          dd.navigateBack({
            delta: 1
          });
        } else {
          dd.reLaunch({
            url: '/pages/index/index'
          });
        }
      } else {
        dd.showToast({
          type: 'fail',
          content: res.data.message,
          duration: 2000
        });
      }
    } catch (err) {
      dd.showToast({
        type: 'fail',
        content: '网络错误，请稍后重试',
        duration: 2000
      });
    } finally {
      this.setData({ isSubmitting: false });
    }
  },
  
  // 新增成功模态框
  async showSuccessModal(message) {
    return new Promise(resolve => {
      dd.showToast({
        type: 'success',
        content: message,
        duration: 1500,
        success: resolve
      });
    });
  },
  
  // 统一错误处理
  showErrorToast(message) {
    dd.showToast({
      type: 'fail',
      content: message,
      duration: 2000
    });
  }
});
